package com.tiantian.subject.dubbo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.tiantian.api.RemoteUserSolveService;
import com.tiantian.api.domain.vo.RemoteUserSolveVo;
import com.tiantian.common.core.exception.BusinessException;
import com.tiantian.subject.domain.entity.UserSolve;
import com.tiantian.subject.mapper.UserSolveMapper;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author tiantian
 */
@RequiredArgsConstructor
@Service
@DubboService
public class RemoteUserSolveServiceImpl implements RemoteUserSolveService {

    private final UserSolveMapper userSolveMapper;

    @Override
    public String getLastReplyTime(Long userId) {
        return userSolveMapper.selectLastReplyTime(userId);
    }

    @Override
    public RemoteUserSolveVo getUserSolveById(String replyId) {
        UserSolve userSolve = userSolveMapper.selectById(replyId);
        return BeanUtil.copyProperties(userSolve, RemoteUserSolveVo.class);
    }

    @Override
    public String getJudgerNameByUserId(Long userId) {
        return userSolveMapper.selectJudgerByUserId(userId);
    }

    @Override
    public List<String> getUserAnswerRecordIds(Long replyUserId) {
        List<UserSolve> userSolves = userSolveMapper.selectByUserId(replyUserId);
        if (CollUtil.isNotEmpty(userSolves)) {
            return userSolves.stream().map(UserSolve::getReplyId).toList();
        }
        return new ArrayList<>();
    }

    @Override
    public Long getReplyUserIdByReplyIds(List<String> replyIds, Long userId) {
        // 判断该判题人是否有权限进行评分
        Long replyUserId = null;
        List<UserSolve> sysJudgeScoreList = userSolveMapper.selectByIds(replyIds);
        for (UserSolve userSolve : sysJudgeScoreList) {
            Long judgerId = userSolve.getJudgerId();
            // 当判题人不是当前用户时
            replyUserId = userSolve.getUserId();
            if (!Objects.equals(userId, judgerId)) {
                return null;
            }
        }
        return replyUserId;
    }
}
